<?php

namespace App\Http\Middleware;

use App\Exceptions\LoginException;
use App\Helpers\MvcHelper;
use App\Traits\GetService\GetUserServiceTrait;
use Closure;
use Exception;
use Illuminate\Http\Request;

class StoreAuthMiddleware
{
    use GetUserServiceTrait;

    /**
     * @throws LoginException
     * @throws Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $token = MvcHelper::getLoginToken();
        // 判断 token 是否有效
        $userInfo = verifyJwt($token);
        // 检测用户是否存在
        $userData = $this->getUserService()->getCheckUserInfo($userInfo['userId']);
        if (empty($userData)) {
            throw new LoginException('登录状态失效，请重新登录', LoginException::CODE_1000);
        }
        if ($userData['status'] != 0) {
            throw new LoginException('登陆失败! 用户被禁止登录!', LoginException::CODE_1002);
        }
        // 暂存token过期时间(为了全局获取，退出登录时加入jwt黑名单用)
        MvcHelper::makeLoginTokenExpire($userInfo['exp']);

        // 设置用户缓存
        MvcHelper::setUserInfCache($userData);

        return $next($request);
    }
}
